<template>
	<view>
		<view class="text-container" @click="dianji">
			<template v-for="(item, index) in parsedTextShow" :key="index">
				<template v-if="item.type === 'text'">
					<text 
						v-for="(word, wordIndex) in item.words" 
						:key="wordIndex"
						@longpress="longpressEvent(word, wordIndex, index, $event)"
						:class="{ actived: isInArray(word, wordIndex, index) }"
					>{{ word }}</text>
					<view v-if="index < parsedTextShow.length - 1" style="height: 50rpx" tag="这里是换行标签"></view>
				</template>
				<view v-else-if="item.type === 'view'"></view>
			</template>
		</view>
	</view>
	<view class="tankbox" :class="{show: tankStatus}" :style="'top:'+(tankStatus ? axes.y : -99999)+'px; left: '+ (tankStatus ? axes.x : -99999) + 'px'">
		<view class="word text-34">{{currentVal.word}}</view>
		<view class="btn" @click="joinEvent">+ 加入生词</view>
	</view>
</template>

<script setup>
import { postWordJoin_api, getArticleWordsList_api } from '@/common/apis/course'
import { watch, ref, reactive, getCurrentInstance } from 'vue';

const { proxy } = getCurrentInstance()
const props = defineProps({
	text: String,
	articleId: String
})

const emit = defineEmits(['callback'])
	
// const text = "When early human skilled a mammoth (a huge prehistoric animal) , how did they keep the meat? <div></div><div></div> We do know;";
const symbols = ["(", ")", ",", "?", ";"];

const parsedTextShow = ref([])

const arrayObjects = ref([]);
const templist = ref([])
const isInArray = (data, index, parentIndex) => {
	const inArrayObjects = arrayObjects.value.some(obj => obj.word === data) && isShow.value;
	const inTempList = templist.value.some(obj => obj.word === data);
    return inArrayObjects || inTempList;
}

watch(() => props.articleId, async newVal => {
	if(newVal){
		arrayObjects.value = await getArticleWordsList_api({articleId: newVal})
	}
})

watch(() => props.text, (newVal) => {
	if(newVal){
		let parsedText = newVal.split(/(<\/?div>|[\s(),?;\.])/);
		let parsedTexts = ''
		parsedTexts = parsedText.reduce((acc, curr) => {
			if (curr === "<div>") {
				acc.push({ type: "view" });
			} else if (curr === "</div>") {
				// do nothing
			} else if (symbols.includes(curr)) {
				if (acc.length > 0) {
					const lastItem = acc[acc.length - 1];
					if (lastItem && lastItem.type === "text") {
						if (curr.trim() !== '') {
						lastItem.words.push(curr);
						}
					} else {
						acc.push({ type: "text", words: curr.trim() !== '' ? [curr] : [] });
					}
				}
			} else {
				const lastItem = acc[acc.length - 1];
				if (lastItem && lastItem.type === "text") {
					if (curr.trim() !== '') {
						lastItem.words.push(curr);
					}
				} else {
					acc.push({ type: "text", words: curr.trim() !== '' ? [curr] : [] });
				}
			}
			return acc;
		}, []);
		
		parsedTextShow.value = parsedTexts.filter(item => item.words && item.words.length > 0);
		console.log(parsedTextShow.value)
	}
}, {immediate: true})

const axes = reactive({
	x: 0,
	y: 0
})
const currentVal = reactive({
	word: '',
	parentIndex: 0,
	index: 0
})
const tankStatus = ref(false)
function longpressEvent(word, index, parentIndex, events){
	if(templist.value.length){
		templist.value = []
	}
	currentVal.word = word
	currentVal.parentIndex = parentIndex
	currentVal.index = index
	templist.value.push({word, indexs: index, parentIndex})
	
	
	let sys = uni.getSystemInfoSync()
	
	setTimeout(() => {
		// #ifdef APP
		const query = uni.createSelectorQuery().in();
		// #endif
		// #ifdef MP-WEIXIN
		const query = uni.createSelectorQuery().in(proxy);
		// #endif
		console.log(query)
		query.select('.tankbox').boundingClientRect(data => {
			if (data) {
				const width = data.width;
				// #ifdef APP
				const {pageX, pageY} = events.touches[0]
				axes.x = (sys.screenWidth - pageX) > width ? pageX : (pageX - width)
				axes.y = pageY
				// #endif
				
				// #ifdef MP-WEIXIN
				const {x, y} = events.detail
				axes.x = (sys.screenWidth - x) > width ? x : (x - width)
				axes.y = y
				// #endif
				tankStatus.value = true
			}
		}).exec();
	})
}

async function joinEvent(){
	const {word, parentIndex, index} = currentVal
	if (word === '.') {
		uni.$fui.toast('请选择英文单词哦~');
		return;
	};
	
	
	arrayObjects.value.push({word, indexs: index, parentIndex})
	let res = await postWordJoin_api({articleId: props.articleId, word })
	console.log(res)
	templist.value = []
	uni.showToast({
		title: '加入成功',
		icon: 'success'
	})
	tankStatus.value = false
	emit('callback')
}

function dianji(){
	if(tankStatus.value){
		tankStatus.value = false
		templist.value.pop()
	}
}

// 是否显示生词
const isShow = ref()
function changeStatus(){
	isShow.value = !isShow.value
}

defineExpose({
	changeStatus
})
</script>

<style lang="scss" scoped>
.text-container{
	display: flex;
	flex-wrap: wrap;
	line-height: 55rpx;
	font-size: 36rpx;
}
text {
  margin-right: 5px;
}
view{
	flex-basis: 100%;
}
.actived{
	background-color: #0b9aff;
	color: #fff;
}
.tankbox{
	position: fixed;
	background-color: #fff; 
	border-radius: 12rpx;
	box-shadow: 0 0 10rpx rgba(0,0,0,0.5);
	padding: 0 30rpx;
	opacity: 0;
	.word{
		font-weight: 600;
		padding: 20rpx 0;
		border-bottom: 1px solid #f0f2f4;
	}
	.btn{
		text-align: center;
		padding: 20rpx 0;
		color: #0b9aff;
		font-size: 28rpx;
	}
	&.show{
		opacity: 1;
	}
}
</style>
